<template>
	<el-breadcrumb separator="/">
		<el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
		<el-breadcrumb-item>课程管理</el-breadcrumb-item>
		<el-breadcrumb-item>课程评价管理</el-breadcrumb-item>
	</el-breadcrumb>
	<div>
		<el-form :inline="true" :model="searchForm" class="demo-form-inline">
			<el-form-item label="课程名称:">
				<el-input v-model="searchForm['course.courseName']" placeholder="请输入课程名称" clearable
					:suffix-icon="Search" @clear="handleClear" />
			</el-form-item>
			<el-form-item>
				<el-button type="primary" @click="onSubmit">搜索</el-button>
				<el-button type="danger" @click="batchDelete">批量删除</el-button>
			</el-form-item>
		</el-form>
	</div>
	<el-table :data="tableData" style="width: 100%" border @selection-change="handleSelectionChange">
		<el-table-column type="selection" fixed prop="id" label="ID" width="60" />
		<el-table-column prop="id" label="id" width="60" />
		<el-table-column prop="user.nickname" label="用户名" width="120" />
		<el-table-column prop="content" label="评价内容" width="860" />
		<el-table-column prop="score" label="评分" width="60" />
		<el-table-column prop="evaluateTime" label="评论时间" width="180" />
		<el-table-column prop="course.courseName" label="课程名称" width="180" />
		<el-table-column fixed="right" label="操作" min-width="150">
			<template #default="scope">
				<el-button type="danger" size="small" @click="remove(scope.row.id)">
					删除
				</el-button>
			</template>
		</el-table-column>
	</el-table>
	<el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[3, 5, 10, 15]"
		:size="size" :background="background" layout="total, sizes, prev, pager, next, jumper" :total="total"
		@size-change="handleSizeChange" @current-change="handleCurrentChange" />
</template>

<script setup>
	import axios from 'axios'
	import {
		onMounted,
		reactive,
		ref
	} from 'vue'
	import {
		Search
	} from '@element-plus/icons-vue'
	import {
		ElMessage,
		ElMessageBox
	} from "element-plus";

	const flname = ref('')
	const currentId = ref(0) // 新增：存储当前编辑的分类ID

	const dialogFormVisible = ref(false)
	const dialogFormVisible1 = ref(false)

	const remove = (id) => {
		ElMessageBox.confirm(
				'请确认是否删除?',
				'Warning', {
					confirmButtonText: '确认',
					cancelButtonText: '取消',
					type: 'warning',
				}
			).then(() => {
				axios.delete(`http://localhost:8080/courseEvaluate/${id}`)
					.then(response => {
						console.log(':+++++', response, id);
						if (response.data.code == 200) { // 使用response.status检查状态码
							ElMessage({
								type: 'success',
								message: '删除成功',
							});
							// 处理成功情况的其他逻辑
						} else {
							ElMessage({
								type: 'error',
								message: '删除失败，状态码：' + response.status, // 显示具体状态码
							});
						}
					})
					.catch(error => {
						console.log(error);
						ElMessage({ // 在捕获错误时也通知用户
							type: 'error',
							message: '请求失败，请稍后再试',
						});
					})
					.finally(() => {
						query(); // 确保query函数已定义
					});
			})
			.catch(() => {
				ElMessage({
					type: 'info',
					message: '取消删除',
				});
			});
	}

	const detailArea = ref('')
	const selectedAddresses = ref([]) // 当前选中的地址数组

	const handleChangeAddress = (d) => {
		// 处理地址变更逻辑
	}

	// 修改：将formInline改为searchForm，并使用与后端匹配的参数名
	const searchForm = reactive({
		'course.courseName': "", // 搜索条件：课程名称
	})

	const courseClassify = {
		id: 0,
		courseClassifyName: ''
	};

	let tableData = ref([])
	const selectedRows = ref([]);
	const tableRef = ref(null);
	const total = ref(0)
	const currentPage = ref(1)
	const pageSize = ref(10)

	// 基础查询函数，合并了原有query和onSubmit的功能
	const query = (params = {}) => {
		// 构建查询参数，合并搜索条件和分页信息
		const queryParams = {
			...searchForm, // 包含搜索条件
			pageSize: pageSize.value,
			pageNum: currentPage.value,
			...params // 允许传递额外参数
		};

		// 构建URL参数
		const urlParams = new URLSearchParams(queryParams).toString();

		axios.get(`http://localhost:8080/courseEvaluate/page?${urlParams}`)
			.then(function(response) {
				tableData.value = response.data.data.list
				total.value = response.data.data.total
				console.log(response)
			})
			.catch(function(error) {
				console.log(error);
			})
			.finally(() => {
				console.log(123)
			});
	}

	const add = () => {
		axios.post('http://localhost:8080/courseEvaluate', {
			id: "",
			courseClassifyName: flname.value
		}).then((response) => {
			console.log('qwer', response)
			ElMessage({
				type: 'success',
				message: '新增成功',
			});
			console.log(response);
		}).catch(function(error) {
			ElMessage({
				type: 'error',
				message: '新增失败',
			});
			console.log(error);
		}).finally(() => {
			console.log(123)
			query()
			dialogFormVisible.value = false
		});
	}

	// 修改：简化onSubmit函数，调用统一的query函数
	const onSubmit = () => {
		currentPage.value = 1; // 重置为第一页
		query();
	}

	const change = () => {
		const requestData = {
			id: currentId.value,
			courseClassifyName: flname.value
		};

		axios.put('http://localhost:8080/courseEvaluate', requestData, {
				headers: {
					'Content-Type': 'application/json'
				}
			})
			.then(function(response) {
				console.log(response);
				if (response.data.code === 200) {
					ElMessage({
						type: 'success',
						message: '修改成功',
					});
				} else {
					ElMessage({
						type: 'error',
						message: '修改失败：' + response.data.message,
					});
				}
			})
			.catch(function(error) {
				console.error(error);
				ElMessage({
					type: 'error',
					message: '请求失败，请稍后再试',
				});
			})
			.finally(() => {
				query(); // 刷新数据
				dialogFormVisible1.value = false; // 关闭对话框
			});
	}

	onMounted(() => {
		query()
	})

	const handleClear = () => {
		searchForm.courseName = ""; // 清空搜索条件
		query(); // 重新查询
	}

	const handleSizeChange = (val) => {
		pageSize.value = val
		query()
	}

	const handleCurrentChange = (val) => {
		currentPage.value = val
		query()
	}

	const handleSelectionChange = (val) => {
		selectedRows.value = val;
	}

	const batchDelete = async () => {
		if (selectedRows.value.length === 0) {
			ElMessageBox.alert('至少选择一条数据才能进行删除', {
				confirmButtonText: 'OK',
				callback: (action) => {
					ElMessage({
						type: 'info',
						message: `action: ${action}`,
					})
				},
			})
			return;
		}

		const ids = selectedRows.value.map(row => row.id).join(',');
		try {
			await axios.delete(`http://localhost:8080/courseEvaluate?ids=${ids}`);
			ElMessage({
				type: 'success',
				message: '删除成功',
			});
			query();
		} catch (error) {
			ElMessage({
				type: 'error',
				message: '删除失败',
			});
			console.error(error);
		}
	};

	const bianji = (row) => {
		dialogFormVisible1.value = true;
		flname.value = row.courseClassifyName;
		currentId.value = row.id; // 保存当前编辑的分类ID
	}
</script>

<style>
	.demo-form-inline .el-input {
		--el-input-width: 220px;
	}

	.demo-form-inline .el-select {
		--el-select-width: 220px;
	}

	el-table-column {
		max-height: 150px;
	}

	.avatar-uploader .avatar {
		width: 178px;
		height: 178px;
		display: block;
		border: 1px;
	}

	.avatar-uploader .el-upload {
		border: 1px dashed var(--el-border-color);
		border-radius: 6px;
		cursor: pointer;
		position: relative;
		overflow: hidden;
		transition: var(--el-transition-duration-fast);
	}

	.avatar-uploader .el-upload:hover {
		border-color: var(--el-color-primary);
	}

	.el-icon.avatar-uploader-icon {
		font-size: 28px;
		color: #8c939d;
		width: 178px;
		height: 178px;
		text-align: center;
	}

	.el-breadcrumb {
		border-bottom: 1px solid #EEEEEE;
		padding-bottom: 15px;
		margin-bottom: 10px;
	}

	.el-breadcrumb {
		border-bottom: 1px solid #EEEEEE;
		padding-bottom: 15px;
	}
</style>